class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        g = [set() for _ in range(numCourses)]
        indegrees = [0] * numCourses
        for prerequisite in prerequisites:
            w, v = prerequisite
            g[v].add(w)
            indegrees[w] += 1
        queue = []
        index = 0
        for i in range(numCourses):
            if indegrees[i] == 0:
                queue.append(i)
        while queue:
            v = queue.pop(0)
            index += 1
            for w in g[v]:
                indegrees[w] -= 1
                if indegrees[w] == 0:
                    queue.append(w)
        return index == numCourses